package com.yy.main.app.web;

import com.github.pagehelper.PageInfo;
import com.yy.kit.annotation.HasPers;
import com.yy.kit.collections.YYListKits;
import com.yy.kit.collections.YYMapKits;
import com.yy.kit.object.YYObjectKits;
import com.yy.main.app.mapper.TMenuMapper;
import com.yy.main.app.mapper.TMenuMessageMapper;
import com.yy.main.app.service.IMenuMessageService;
import com.yy.main.app.service.IMenuService;
import com.yy.main.app.web.base.CommonController;
import com.yy.pojo.base.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 杨阳
 * @since 2017-09-20
 */
@Controller
@RequestMapping("/menu")
@Api(value = "菜单的controller", tags = {"菜单与消息关系controller"})
public class MenuController extends CommonController {

    @Resource(name = "iMenuService")
    private IMenuService iMenuService;
    @Resource(name = "iMenuMessageService")
    private IMenuMessageService iMenuMessageService;
    @Autowired
    private TMenuMapper tMenuMapper;
    @Autowired
    private TMenuMessageMapper tMenuMessageMapper;


    /**
     * <p>
     * 跳转到菜单管理页面
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月26日
     */
    @RequestMapping(value = "/menuList", method = RequestMethod.GET)
    @HasPers(name = "menu:manager")
    @ApiOperation(value = "跳转到菜单管理页面", httpMethod = "GET", notes = "跳转到菜单管理页面,需要拥有menu:manager权限")
    public ModelAndView permissionList(HttpSession session) {
        return goToPageByModelAndView("system/menu/menu_list", null, getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 同步菜单到微信
     * </p>
     *
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年10月9日
     */
    @PostMapping("/syncToWeChat")
    @ResponseBody
    public Map<String, Object> syncToWeChat() {
        return null;
    }

    /**
     * <p>
     * 同步菜单到支付宝生活号
     * </p>
     *
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年10月9日
     */
    @PostMapping("/SyncToAlipay")
    @ResponseBody
    public Map<String, Object> syncToAlipay(HttpSession session) {
        return iMenuService.syncToAlipay(getCurrentUser(session).getId());
    }

    /**
     * <p>
     * 获得菜单管理同步树
     * </p>
     *
     * @return {@link List}<Menu>
     * @author 杨阳
     * @since 2017年9月26日
     */
    @ApiOperation(value = "获得菜单管理同步树", httpMethod = "POST", notes = "获得菜单管理同步树,因为数据不多所以一次性返回")
    @RequestMapping(value = "/tree", method = RequestMethod.POST)
    @ResponseBody
    public List<TMenu> tree() {
        TMenuExample example = new TMenuExample();
        example.setOrderByClause("seq asc");
        return tMenuMapper.selectByExample(example);
    }

    /**
     * <p>
     * 获得菜单的详细信息
     * </p>
     *
     * @param id 权限id
     * @author 杨阳
     * @since 2017年9月12日
     */

    @RequestMapping(value = "/get/{id}", method = RequestMethod.POST)
    @ApiOperation(value = "获得菜单的详细信息", httpMethod = "POST", notes = "获得菜单的详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID", required = true, paramType = "path")
    })
    @ResponseBody
    public TMenu get(@PathVariable("id") String id) {
        return tMenuMapper.selectByPrimaryKey(id);
    }

    /**
     * <p>
     * 跳转到编辑菜单的页面
     * </p>
     *
     * @param id 关键字ID
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/menuform/{id}/{parentid}", method = RequestMethod.GET)
    @HasPers(name = "menu:add,menu:update")
    @ApiOperation(value = "跳转到编辑菜单的页面", httpMethod = "GET", notes = "跳转到编辑菜单的页面,需要menu:add,menu:update权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID,如果是增加，那么id一定是-1", required = true, paramType = "path"),
            @ApiImplicitParam(name = "parentid", value = "父菜单id", paramType = "path")
    })
    public ModelAndView menuForm(@PathVariable("id") String id, @PathVariable("parentid") String parentid, HttpServletRequest request) {
        TMenu menu = tMenuMapper.selectByPrimaryKey(id);

        // 查询出与菜单关联的消息列表
        List<TMessage> previewList = iMenuService.selectMessageByMenuId(id);

        // 查询出与菜单关联的消息的消息字符串1,2,3
        TMenuMessageExample example = new TMenuMessageExample();
        example.createCriteria().andMenu_idEqualTo(id);
        List<TMenuMessage> mmList = tMenuMessageMapper.selectByExample(example);

        if (YYObjectKits.isNull(menu)) {
            menu = new TMenu();
            menu.setId("-1");
            menu.setParentid(parentid);
        }
        if (YYListKits.isEmpty(previewList)) {
            previewList = YYListKits.createList();
        }

        StringBuilder msgids = new StringBuilder();

        for (int i = 0; i < mmList.size(); i++) {
            TMenuMessage km = mmList.get(i);
            if (i > 0) {
                msgids.append(",");
            }
            msgids.append(km.getMessage_id());
        }
        Map<String, Object> param = YYMapKits.createHashMap();
        param.put("menu", menu);
        param.put("previewList", previewList);
        param.put("msgid", msgids.toString());
        return goToPageByModelAndView("system/menu/menu_form", param, getCurrentUser(request.getSession()).getId());
    }

    /**
     * <p>
     * 查看菜单详情
     * </p>
     *
     * @return {@link ModelAndView}
     * @author 杨阳
     * @since 2017年9月26日
     */
    @RequestMapping(value = "/show/{id}", method = RequestMethod.GET)
    @HasPers(name = "menu:show")
    @ApiOperation(value = "查看菜单详情", httpMethod = "GET", notes = "查看菜单详情,需要menu:show权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "关键字ID", required = true, paramType = "path")
    })
    public ModelAndView show(@PathVariable("id") String id) {
        TMenu menu = tMenuMapper.selectByPrimaryKey(id);
        Map<String, Object> param = YYMapKits.createHashMap();

        // 查询出与关键字关联的消息列表
        List<TMessage> previewList = iMenuService.selectMessageByMenuId(id);
        if (YYListKits.isEmpty(previewList)) {
            previewList = YYListKits.createList();
        }

        param.put("previewList", previewList);
        param.put("menu", menu);
        return goToPageByModelAndView("system/menu/menu_show", param);
    }

    /**
     * <p>
     * 根据菜单id查询出与之相关联的消息列表
     * </p>
     *
     * @param menuid 关键字id
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    @RequestMapping(value = "/selectMessageByMenuId", method = RequestMethod.GET)
    @ApiOperation(value = "根据菜单id查询出与之相关联的消息列表", httpMethod = "GET", notes = "根据菜单id查询出与之相关联的消息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页记录数", required = true, paramType = "query"),
            @ApiImplicitParam(name = "menuid", value = "菜单id", paramType = "query")
    })
    @ResponseBody
    public Map<String, Object> selectMessageByMenuId(Integer page, Integer limit, String menuid) {
        PageInfo messagePage = iMenuService.selectMessageByMenuId(page, limit, menuid);
        return super.pageToMap(messagePage);
    }

    /**
     * <p>
     * 从菜单中移除消息
     * <p>
     *
     * @param menuid 菜单id
     * @param msgid  消息id
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月22日
     */
    @RequestMapping(value = "/removeMessagesFromMenu/{menuid}/{msgid}", method = RequestMethod.POST)
    @ApiOperation(value = "从菜单中移除消息", httpMethod = "POST", notes = "从菜单中移除消息")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "menuid", value = "菜单ID", paramType = "form"),
            @ApiImplicitParam(name = "msgid", value = "消息ID", paramType = "form")
    })
    public @ResponseBody
    Map<String, Object> removeMessagesFromKeywords(@PathVariable(value = "menuid") String menuid,
                                                   @PathVariable(value = "msgid") String msgid) {
        TMenuMessageExample example = new TMenuMessageExample();
        example.createCriteria()
                .andMenu_idEqualTo(menuid)
                .andMessage_idEqualTo(msgid);
        Integer b = tMenuMessageMapper.deleteByExample(example);

        if (b > 0) {
            return successMap("移除成功!");
        } else {
            return errorMap("移除失败,请重试!");
        }
    }

    /**
     * <p>
     * 删除菜单
     * </p>
     *
     * @param id 关键字id
     * @return {@link Map}
     * @author 杨阳
     * @since 2017年9月21日
     */
    @RequestMapping(value = "/delmenu/{id}", method = RequestMethod.POST)
    @HasPers(name = "menu:delete")
    @ApiOperation(value = "删除菜单", httpMethod = "POST", notes = "删除菜单,需要menu:delete权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "菜单ID", required = true, paramType = "path")
    })
    @ResponseBody
    public Map<String, Object> delmenu(@PathVariable("id") String id) {
        return iMenuService.delMenu(id);
    }

    /**
     * <p>
     * 保存菜单信息
     * </p>
     *
     * @param menu  菜单实体
     * @param msgid 菜单要关联的消息
     * @return {@link Map}<String, Object>
     * @author 杨阳
     * @since 2017年9月21日
     */
    @ApiOperation(value = "保存菜单信息", httpMethod = "POST", notes = "增加或修改菜单")
    @RequestMapping(value = "/savemenu", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveMenu(TMenu menu, String msgid) {
        return iMenuService.saveMenu(menu, msgid);
    }
}
